package com.wx.house.common.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class OriginFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res,
                     FilterChain chain) throws IOException, ServletException {
	HttpServletResponse response = (HttpServletResponse) res;
	HttpServletRequest request = (HttpServletRequest) req;
	
	//*所有的域名  比如说写了 oppo1.9linked.com 就只能放在oppo1服务器上的静态网站来发送异步请求
	response.setHeader("Access-Control-Allow-Origin", "*");
	
	//用于表示用户代理是否应该在跨域请求的情况下从其他域发送cookies
	response.setHeader("Access-Control-Allow-Credentials", "true");
	
	//异步请求的时候允许携带以下请求头
	response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie,authorization");
	
	//允许使用以下方法
	response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");
	
	//导出的请求头，如果这里不加，即使postman里能找到，axios和ajax等等异步请求也会无法收到
	response.setHeader("Access-Control-Expose-Headers", "X-forwarded-port,X-forwarded-host,authorization");
	
	response.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
	response.setHeader("Access-Control-Max-Age", "3600");
	
	//OPTIONS 预备检查服务器  预请求头
	if ("OPTIONS".equals(request.getMethod())) {
		//直接返回code 200 才会执行后面的method
		response.setStatus(200);
		return;
	}
	chain.doFilter(req, res);
}

@Override
public void destroy() {
}

}